$(function () 
{	
	stacking = false;
	keepFetching = true;
	isGraph = false;	
	hideEverything();		
	updatePage();
		
	function hideEverything() {
		$("#choicesHeader").hide();
		$(".choice").hide();
		$(".choices").hide();							
		$(".teacherButtons").hide();				
		$(".analytics").hide();
		$("#correctAnswer").css("visibility", "hidden");
		$("#stackHistogram").hide();				
	}
	function updatePage() {
		$.post("/getDisplays", {questionKey: $("#storeQuestion").attr("title")},								
			function(data) 
			{			
				parsedBooleans = JSON.parse(data);
				try {
					responsesVisible = parsedBooleans[0];
					showData = parsedBooleans[1];
					isTeacher = parsedBooleans[2];
					//update button text based on the current state
					if (responsesVisible)
						$("#responsesVisibleButton").html("Make Private");
					if (showData)
						$("#showDataButton").html("Hide Analytics");
										
					//only students see choices					
					if (isTeacher)  {
																			
						$(".teacherButtons").show();
					}
					//only teacher sees correctAnswer and buttons									
					else  {					
						$("#choicesHeader").show();
						$(".choice").show();
						$(".choices").show();							
					}
					if (!showData)
					{						
						$(".analytics").hide();
						$("#stackHistogram").hide();
					}
					else
						if (!isTeacher && !responsesVisible)
						{
							$(".analytics").hide();
							$("#stackHistogram").hide();
						}
						else {
							if (keepFetching)																												
								gatherAnalytics();							
							$(".analytics").show();																					
							$("#stackHistogram").show();					
						}				
				}
				catch(e) {
					alert("Error in updating page: " + e.toString());
					alert(data);
				}			
			});
	}
	//listen to the showDataButton, default showData = false
	$("#showDataButton").click(function () 
	{		
		currentText = $(this).text();	
		//analytics are currently hidden, so set showData to true
		if (currentText == "Show Analytics")  {					
			$.post("/setDisplays", {questionKey: $("#storeQuestion").attr("title"), editData: "True",
				showData: "True", editResponses: "False", responsesVisible: "False"}, function(data)
			{				
				$("#showDataButton").html("Hide Analytics");
				$(".analytics").show();
				graphAll();	
				$("#stackHistogram").show();
			});							
		}
		else  {			
			$.post("/setDisplays", {questionKey: $("#storeQuestion").attr("title"), editData: "True",
				showData: "False", editResponses: "False", responsesVisible: "False"}, function(data) 
			{				
				$("#showDataButton").html("Show Analytics");
				$(".analytics").hide();		
				$("#stackHistogram").hide();		
			});			
		}		
	});	
	
	//listen to the showDataButton, default showData = false
	$("#showAnswerButton").click(function () 
	{		
		currentText = $(this).text();	
		//analytics are currently hidden, so set showData to true
		if (currentText == "Show Answer")  {							
			$("#correctAnswer").css("visibility", "visible");
			$("#showAnswerButton").html("Hide Answer");
										
		}
		else  {			
			$("#correctAnswer").css("visibility", "hidden");
			$("#showAnswerButton").html("Show Answer");
		}		
	});	
	
	//listen to the responsesVisibleButton, default responsesVisible = false
	$("#responsesVisibleButton").click(function () 
	{		
		currentText = $(this).text();		
		//analytics are currently hidden, so set showData to true
		if (currentText == "Make Public")  {			
			$.post("/setDisplays", {questionKey: $("#storeQuestion").attr("title"), showData: "False",
				showData: "False", editResponses: "True", responsesVisible: "True"}, function(data)
			{				
				$("#responsesVisibleButton").html("Make Private");	
			});				
		}
		else  {			
			$.post("/setDisplays", {questionKey: $("#storeQuestion").attr("title"), showData: "False",
				showData: "False", editResponses: "True", responsesVisible: "False"}, function(data) 
			{				
				$("#responsesVisibleButton").html("Make Public");								
			});
		}				
	});
	//listen to the responsesVisibleButton, default responsesVisible = false
	$("#stackHistogram").click(function () 
	{	
		//unstack
		if (stacking)
			simplePlot();
		else
			stackPlot();
		updatePage();
		stacking = !stacking;		
	});	
	function gatherAnalytics() {		
		aSelected = 0;
		bSelected = 0;
		cSelected = 0;
		dSelected = 0;
		eSelected = 0;
		
		$.post("/getAnswers", {categoryKey: $("#storeCategory").attr("title"),
			questionKey: $("#storeQuestion").attr("title")}, function(data) 
		{		
			try {
				totalTime = parseInt($("#storeTime").attr("title"));							
				studentResponses = JSON.parse(data);
				interval = 5; //categorize time stamps by 10second intervals
				//initialize some sort of array that keeps a count of each interval 	 			 	 			
 	 			indexArray = [];	 			
 	 			timeThird = parseInt(totalTime / 3);
 	 			stackedArray = new Array(3);
 	 			 	 			 			
 	 			for (i = 0; i <= totalTime / interval; i++) 	 			
 	 				indexArray[i] = 0;	 				 	 			 	 			
 	 			for (i = 0; i < stackedArray.length; i++) 	 			
 	 				stackedArray[i] = [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]];
 	 							
				jQuery.each(studentResponses, function()
				{
					studentResponse = this.studentResponse;
					//invariant: that 0 < timeTaken < timeToAnswer
					timeTaken = this.timeElapsed;
					//STOP entry, ignore this response
					if (timeTaken < 0) 
					{
						keepFetching = false;										
						return false;						
					}
					index = parseInt(this.timeElapsed / interval)					
					//protects against an array out of bounds exception
					if (this.timeElapsed == totalTime)
						this.timeElapsed--;					
					stackIndex = parseInt(this.timeElapsed / timeThird);					
					indexArray[index]++
					if (studentResponse == "A")	{
						aSelected++;
						stackedArray[stackIndex][0][1]++;
					}
					else if (studentResponse == "B"){
						bSelected++;
						stackedArray[stackIndex][1][1]++;
					}
					else if (studentResponse == "C"){
						cSelected++;
						stackedArray[stackIndex][2][1]++;
					}
					else if (studentResponse == "D"){
						dSelected++;
						stackedArray[stackIndex][3][1]++;
					}
					else{
						eSelected++;
						stackedArray[stackIndex][4][1]++;
					}
				});						
				timeData = []; 	
				jQuery.each(indexArray, function(index, value){
					//sampleArray[0].push([index * interval, indexArray[index]]);
					//alert("pushed");									
					timeData.push([index * interval, indexArray[index]]);					
				});						    
				d1 = new Array(5);
				for (i = 0; i < d1.length; i++)	{
					d1[i] = [i, 0];					
				}
    			/*alert("A: " + aSelected);
    			alert("B: " + bSelected);
    			alert("C: " + cSelected);
    			alert("D: " + dSelected);
    			alert("E: " + eSelected);*/   			
			   	d1[0][1] = aSelected;
			   	d1[1][1] = bSelected;
			   	d1[2][1] = cSelected;
			   	d1[3][1] = dSelected;
			   	d1[4][1] = eSelected; 
			   	
			   	if (!isGraph)
			   	{
			   		graphAll();
			   		isGraph = true;
			   	}
			   	   			  														
 	 	} catch(e) { 	 			
 	 			alert("error in getting answer: " + e.toString()); 	 
 	 			alert(data);			
 	 		}
		}); 
	}
	function graphAll()
	{
		if (stacking)
			stackPlot();
		else
			simplePlot();					
    	timePlot(); 
	}
	//plots basic graphs
	function simplePlot() {    
        $.plot($("#responseholder"), [ d1 ], {
            series: {
                stack: 0,                
                lines: { show: false, fill: true, steps: false},
                bars: { show: true, barWidth: 0.6, align: "center"},
                color: "black"
            },
            xaxis: {ticks: [[0,'A'], [1,'B'], [2,'C'], [3,'D'], [4,'E']]},
        });            
    }
    //plots time submitted
    function timePlot() {
    	$.plot($("#timeholder"), [ timeData ], {
            series: {
                stack: 0,                
                lines: { show: false, fill: true, steps: false},
                bars: { show: true, barWidth: 0.6 * interval, align: "center"},
                color: "black"
            }
        }); 
    }
    //plots a stacked histogram, based on time   
    function stackPlot() {
    	
    	var data = [{ label: "First " + timeThird + " seconds", data: stackedArray[0] }, 
    				{ label: "Middle " + timeThird + " seconds", data: stackedArray[1] }, 
    				{ label: "Last " + timeThird + " seconds", data: stackedArray[2] },];
    	$.plot($("#responseholder"), data, 
    	{
            series: {
                stack: true,                
                lines: { show: false, fill: true, steps: false},
                bars: { show: true,	barWidth: 0.6, align: "center" }                                    	
            },
            xaxis: {ticks: [[0,'A'], [1,'B'], [2,'C'], [3,'D'], [4,'E']]},
        });          	
    }    
    //handles student choices    	  	
	$(".choice").click(function() 
	{	
		selected = $(this)		
		if (true) {		
			$(selected).css("background-color", "orange");		
			$.post("/ansQuestion", {studentResponse: $(this).attr("title"),
			courseKey: $("#storeCourse").attr("title"), 
			categoryKey: $("#storeCategory").attr("title"),
			questionKey: $("#storeQuestion").attr("title")}, 
			function (data) 
			{			
				$(".choice").css("background-color", "#FFDAA3");		
				if (data == "Success")		
				{												
					$(selected).css("background-color", "green");
					awesome = $(selected)
				}			
				else
				{				
					$(selected).css("background-color", "red");
					$(awesome).css("background-color", "green");				
				}								
			});				
		}	
	});		
});